package com.lanou.connotationjoke.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;
import com.google.gson.Gson;
import com.lanou.connotationjoke.R;
import com.lanou.connotationjoke.adapter.DiscoveryHotListViewAdaper;
import com.lanou.connotationjoke.entity.AppUrl;
import com.lanou.connotationjoke.entity.BannerDetialEty;
import com.lanou.connotationjoke.entity.BannerUrlEty;
import com.lanou.connotationjoke.entity.DiscoveryEty;
import com.lanou.connotationjoke.tool.VolleySingleton;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.zip.Inflater;

/**
 * Created by dllo on 16/1/21.
 */
public class DiscoveryHotFragment extends BaseFragment{
    private String URL = AppUrl.DISCOVERY;
    private DiscoveryEty discoveryEty;
    private ListView listView;
    private DiscoveryHotListViewAdaper listViewAdaper;
    private View headView;


   //轮播图..
    int[] dotIds = {R.id.dot_0, R.id.dot_1,R.id.dot_2, R.id.dot_3, R.id.dot_4};
    private List<View> dots;
    private TextView title;
    private ViewPager mViewPager;
    private ViewPagerAdapter adapter;
    private List<String> titles;
    private List<NetworkImageView> images;
    private int oldPosition = 0;//记录上一次点的位置
    private int currentItem; //当前页面
    private ScheduledExecutorService scheduledExecutorService;
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            //设定时间自动翻页的回调方法
            mViewPager.setCurrentItem(currentItem);
            return false;
        }
    });


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_discovery_hot,null);
        listView = (ListView) view.findViewById(R.id.listview_discovery);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        VolleySingleton.addRequest(URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                discoveryEty = gson.fromJson(response,DiscoveryEty.class);
                initHeadView();
                listView.addHeaderView(headView);
                listViewAdaper = new DiscoveryHotListViewAdaper(getActivity(),discoveryEty);
                listView.setAdapter(listViewAdaper);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });


    }



    private void initHeadView(){

        headView = LayoutInflater.from(getActivity()).inflate(R.layout.shuffling_figure,null);
        title = (TextView) headView.findViewById(R.id.title_shuffling_figure);
        mViewPager = (ViewPager) headView.findViewById(R.id.viewpager_shuffling_figure);
        dots = new ArrayList<>();
        titles = new ArrayList<>();
        images = new ArrayList<>();
        //根据图片的个数计算第一个点得位置
        int i = dotIds.length - discoveryEty.getData().getRotate_banner().getCount();
        Log.d("s",""+dots.size());
        List<BannerDetialEty>  bannerDetialEties =
                discoveryEty.getData().getRotate_banner().getBanners();
        for (BannerDetialEty bannerDetialEty:bannerDetialEties){
            titles.add(bannerDetialEty.getBanner_url().getTitle());
            View dot = headView.findViewById(dotIds[i]);
            dot.setVisibility(View.VISIBLE);
            dots.add(dot);
            NetworkImageView imageView = new NetworkImageView(getActivity());
            imageView.setDefaultImageResId(R.mipmap.ic_launcher);
            imageView.setErrorImageResId(R.mipmap.ic_launcher);
            imageView.setImageUrl(bannerDetialEty.getBanner_url().getUrl_list().get(0).getUrl()
                    , VolleySingleton.getImageLoader());
            images.add(imageView);
            ++i;
        }
        title.setText(titles.get(0));
        adapter = new ViewPagerAdapter();
        mViewPager.setAdapter(adapter);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                title.setText(titles.get(position));
                dots.get(oldPosition).setBackgroundColor(Color.WHITE);
                dots.get(position).setBackgroundColor(Color.GREEN);
                oldPosition = position;
                currentItem = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

        //每隔2秒钟切换一张图片
        scheduledExecutorService.scheduleWithFixedDelay(new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                currentItem = (currentItem +1) % titles.size();
                //更新界面
                handler.obtainMessage().sendToTarget();
            }
        }), 2, 2, TimeUnit.SECONDS);




    }




    private class ViewPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return images.size();
        }

        //是否是同一张图片
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup view, int position, Object object) {
            view.removeView(images.get(position));

        }

        @Override
        public Object instantiateItem(ViewGroup view, int position) {
            view.addView(images.get(position));
            return images.get(position);
        }
    }


}
